<template>
	<custom-range-vue @update-between-time="handleBetweenTime" :showLeft="showLeft" :showBack="false"
		class="customRange">
		<!-- 具名插槽---区域类型 -->
		<template v-slot:custom>
			<view class="tabs p-b-15">
				<view style="width: 100%;padding: 0 30rpx;box-sizing: border-box;">
					<scroll-view scroll-x="true" style="white-space: nowrap;width: 100%;" :show-scrollbar="false">
						<view style="display: flex; flex-direction: row;padding-right: 60rpx;">
							<view v-for="(item,index) in tabs" :key="index" class="m-r-40 p-b-10 f-s-28 tab-text"
								:class="{'bor-bot-active tab-text-active':act == index}" @click="clickTab(index)">
								{{item.shop_alias}}
							</view>
						</view>
					</scroll-view>
				</view>
			</view>
		</template>
	</custom-range-vue>
	<scroll-view class="scroll" scroll-y :style="{'height':scrollHeight,'top':scrollTop}" :show-scrollbar="false" :scroll-top="top" @scroll="scroll">
		<view class="f-s-28 bold-text p-t-16">
			<text class="title" style="font-weight: 600;">数据统计</text>
		</view>
		<view class="total-box flex m-t-20 flex-row flex-jus-bet">
			<view class="flex flex-col flex-jus-cen"
				style="background-color: var(--bg-center-color);border-radius: 10rpx;padding: 20rpx 0;width: 32%;">
				<view class="title" style="color: var(--grey-text);">
					总消费
				</view>
				<view class="bold-text m-t-20 m-b-20"
					style="font-size: 30rpx;color: var(--white-text);font-weight: 500;">
					{{total}}
					<text class="unit">万</text>
				</view>
				<view class="flex">
					<text :class="totalRate>=0?'red-text':'green-text'">
						<text>{{totalRate>=0?'+':totalRate<0?'-':''}}{{Math.abs(totalRate)}}</text>%
					</text>
				</view>
			</view>
			<view class="flex flex-col flex-jus-cen"
				style="background-color: var(--bg-center-color);border-radius: 10rpx;padding: 20rpx 0;width: 32%;">
				<view class="title" style="color: var(--grey-text);">总营业</view>
				<view class="bold-text red-text m-t-20 m-b-20"
					style="font-size: 30rpx;color: var(--white-text);font-weight: 500;">
					{{fact}}
					<text class="unit">万</text>
				</view>
				<view class="flex">
					<text :class="factRate>=0?'red-text':'green-text'">
						<text>{{factRate>=0?'+':factRate<0?'-':''}}{{Math.abs(factRate)}}</text>%
					</text>
				</view>
			</view>
			<view class="flex flex-col flex-jus-cen"
				style="background-color: var(--bg-center-color);border-radius: 10rpx;padding: 20rpx 0;width: 32%;">
				<view class="title" style="color: var(--grey-text);">总收款</view>
				<view class="bold-text red-text m-t-20 m-b-20"
					style="font-size: 30rpx;color: var(--white-text);font-weight: 500;">
					{{rec}}
					<text class="unit">万</text>
				</view>
				<view class="flex">
					<text :class="recRate>=0?'red-text':'green-text'">
						<text>{{recRate>=0?'+':recRate<0?'-':''}}{{Math.abs(recRate)}}</text>%
					</text>
				</view>
			</view>
		</view>
		
		<view class="f-s-28 bold-text m-t-20">
			<text class="title" style="font-weight: 600;">营业数据</text>
		</view>
		<view style="background: var(--bg-center-color);border-radius: 10rpx;" class="m-t-20 p-t-10 p-b-10">
			<view class="m-b-20 m-t-10">
				<text style="font-size: 24rpx;color: var(--grey-text);">*近五日营业数据概况</text>
			</view>
			<view class="tab-head tab-item flex-ali-cen">
				<view class="title" style="color: var(--grey-text);">日期</view>
				<view class="title" style="color: var(--grey-text);">消费(万)</view>
				<view class="red-text" style="font-size: 28rpx;">营业(万)</view>
				<view class="flex flex-jus-end title" style="color: var(--grey-text);">收款(万)</view>
			</view>
			<view class="tab-container ">
				<view v-for="(it, idx) in factList" :key="idx" class="tab-item flex-ali-cen">
					<view style="font-size: 28rpx;color: var(--white-text);font-weight: 500;">{{it.date}}</view>
					<view style="font-size: 28rpx;color: var(--white-text);font-weight: 500;">{{it.total_money}}</view>
					<view class="red-text" style="font-size: 28rpx;">{{it.fact_money}}</view>
					<view class="flex flex-jus-end" style="font-size: 28rpx;color: var(--white-text);font-weight: 500;">{{it.receipts_money}}</view>
				</view>
			</view>
			<view class="m-b-20 m-t-10">
				<text style="font-size: 24rpx;color: var(--grey-text);">*近七日营业数据走势</text>
			</view>
			<view class="cavas m-t-10 p-b-20">
				<qiun-data-charts ref="chart" type="tarea" :opts="opts" :chartData="chartData" />
			</view>
		</view>
		<view class="f-s-28 bold-text m-t-20">
			<text class="title" style="font-weight: 600;">开台数据</text>
		</view>
		<view style="background: var(--bg-center-color);border-radius: 10rpx;" class="m-t-20 p-t-10 p-b-10">
			<view class="m-b-20 m-t-10">
				<text style="font-size: 24rpx;color: var(--grey-text);">*近五日开台数据概览</text>
			</view>
			<view class="tab-head tab-item flex-ali-cen">
				<view class="title" style="color: var(--grey-text);">日期</view>
				<view class="title" style="color: var(--grey-text);">开台数(桌)</view>
				<view class="red-text" style="font-size: 28rpx;">开台率(%)</view>
				<view class="flex flex-jus-end title" style="color: var(--grey-text);">桌均消(元)</view>
			</view>
			<view class="tab-container ">
				<view v-for="(it, idx) in factList" :key="idx" class="tab-item flex-ali-cen">
					<view style="font-size: 28rpx;color: var(--white-text);font-weight: 500;">{{it.date}}</view>
					<view style="font-size: 28rpx;color: var(--white-text);font-weight: 500;">{{it.fact_room}}</view>
					<view class="red-text" style="font-size: 28rpx;">{{it.open_rate}}</view>
					<view class="flex flex-jus-end" style="font-size: 28rpx;color: var(--white-text);font-weight: 500;">{{it.avg_room_money}}</view>
				</view>
			</view>
			<view class="m-b-20 m-t-10">
				<text style="font-size: 24rpx;color: var(--grey-text);">*近七日开台率走势</text>
			</view>
			<view class="cavas m-t-10 p-b-20">
				<qiun-data-charts ref="chart" type="tarea" :opts="opts1" :chartData="chartData1" />
			</view>
		</view>
		<bottom-company-vue :footerStyle="footerStyle"></bottom-company-vue>
	</scroll-view>
	<custom-loading-vue ref="loading"></custom-loading-vue>
	<tab-bar-vue :act="1"></tab-bar-vue>
		
</template>

<script setup>
	import {
		nextTick,
		onMounted,
		ref,
		watch,
		getCurrentInstance,
		onBeforeMount
	} from 'vue'
	import dayjs from 'dayjs';
	import {
		deepClone
	} from '@/utils/index.js'
	import customRangeVue from '@/components/customRange.vue'
	import customLoadingVue from '@/components/customLoading.vue'
	import bottomCompanyVue from '@/components/bottomCompany.vue'
	import tabBarVue from "@/components/tabBar.vue"

	const instance = getCurrentInstance()
	const commonJs = instance?.proxy?.$commonJs
	const footerStyle = ref({
		padding: '40rpx 0'
	})
	const scrollHeight = ref('0px')
	const scrollTop = ref('0px')
	const topHeight = ref(0)
	const showLeft = ref(false)
	const betweenTime = ref([])
	const loading = ref(Object)
	const tabs = ref([])
	const act = ref(0)
	const total = ref('')
	const totalRate = ref(0)
	const fact = ref(0)
	const factRate = ref(0)
	const rec = ref(0)
	const recRate = ref(0)
	const factList = ref([])
	const chartData = ref({})
	const chartData1 = ref({})
	const chart = ref()
	const opts = {
		color: ["#e87d7d"],
		padding: [10, 20, 0, 0],
		enableScroll: false,
		legend: {
			show: false
		},
		toolTip: {
			showArrow: false
		},
		xAxis: {
			calibration: true,
			disableGrid: true,
			boundaryGap: "center",
			// format: "xAxisDemo2",
			itemCount: 7
		},
		yAxis: {
			showTitle: true,
			gridType: "dash",
			disableGrid: true,
			dashLength: 2,
			data: [{
				title: '营业额(万)',
				titleOffsetX: 10,
				titleFontSize: 12,
				min: 0,
				max: 100
			}]
		},
		extra: {
			area: {
				type: "curve",
				opacity: 1,
				addLine: true,
				width: 2,
				gradient: true,
				activeType: "none"
			}
		}
	}
	const opts1 = {
		color: ["#00aa00"],
		padding: [10, 20, 0, 0],
		enableScroll: false,
		legend: {
			show: false
		},
		toolTip: {
			showArrow: false
		},
		xAxis: {
			calibration: true,
			disableGrid: true,
			boundaryGap: "center",
			// format: "xAxisDemo2",
			itemCount: 7
		},
		yAxis: {
			showTitle: true,
			gridType: "dash",
			disableGrid: true,
			dashLength: 2,
			data: [{
				title: '开台率(%)',
				titleFontSize: 12,
				min: 0,
				max: 100
			}]
		},
		extra: {
			area: {
				type: "curve",
				opacity: 1,
				addLine: true,
				width: 2,
				gradient: true,
				activeType: "none"
			}
		}
	}
  const top = ref(0)
  const old = ref({
    scrollTop: 0
  })

	onBeforeMount(() => {
		getTabs()
	})
  onMounted(() => {
    getLine()
    const query = uni.createSelectorQuery().in(this);
    query.select(".customRange")
        .boundingClientRect((data) => {
          scrollTop.value = data.height + 'px'
          let topHeight = data.height + 'px'
          scrollHeight.value = `calc(100vh - ${topHeight} - 50px)`
        })
        .exec();
  })
	watch(betweenTime, async (newValue, oldValue) => {
		if (JSON.stringify(newValue) !== JSON.stringify(oldValue)) {
      resetPages()
			getData()
		}
	}, {
		deep: true
	})
	const handleBetweenTime = (timeRange) => {
		betweenTime.value = timeRange
	}

  const scroll = (e) => {
    old.value.scrollTop = e.detail.scrollTop
  }

  /**
   * 重置scroll-view置顶
   */
  const resetPages = ()=>{
    top.value = old.value.scrollTop
    nextTick(() => {
      top.value = 0
    })
  }

	const getData = () => {
		const params = {
			group_id: commonJs.getRequestShopId(),
			begin_date: betweenTime.value[0] + ' 12:00:00',
			end_date: betweenTime.value[1] + ' 12:00:00',
			staff_id: commonJs.getUserInfo().staff_id,
			shop_id: tabs.value[act.value].shop_id
		}
		commonJs.queryCache('/group/getGroupBusinessByShop', params, {
			before() {
				loading.value.show('加载中...')
			},
			success(res) {
				try {
					const now = res.data.now
					const before = res.data.before
					total.value = (now.total_money / 10000).toFixed(2)
					totalRate.value = before.total_money > 0 ? ((now.total_money - before.total_money) / before
						.total_money * 100).toFixed(2) : now.total_money > 0 ? '100' : '0'
					fact.value = (now.fact_money.total_money / 10000).toFixed(2)
					factRate.value = before.fact_money.total_money > 0 ? ((now.fact_money.total_money - before
							.fact_money
							.total_money) / before.fact_money.total_money * 100).toFixed(2) : now.fact_money
						.total_money >
						0 ? '100' : '0'
					rec.value = (now.receipts_money.total_money / 10000).toFixed(2)
					recRate.value = before.receipts_money.total_money > 0 ? ((now.receipts_money.total_money -
							before
							.receipts_money.total_money) / before.receipts_money.total_money * 100).toFixed(
							2) : now
						.receipts_money.total_money > 0 ? '100' : '0'
				} catch (error) {
					commonJs.showMessage(error)
				}
			},
			fail(err) {
				commonJs.logger.debug(err, 'error')
			},
			complete() {
				loading.value.hide()
			}
		})
	}
	const getLine = () => {
		const params = {
			group_id: commonJs.getRequestShopId(),
			staff_id: commonJs.getUserInfo().staff_id,
			shop_id: tabs.value[act.value].shop_id
		}
		commonJs.queryCache('/group/getGroupBusinessByDate', params, {
			before() {
				
			},
			success(res) {
				try {
					res.data.forEach(it => {
						it.date = dayjs(it.date).format('D号')
						it.total_money = (it.total_money / 10000).toFixed(2)
						it.fact_money = (it.fact_money / 10000).toFixed(2)
						it.receipts_money = (it.receipts_money / 10000).toFixed(2)
					})
						setChart(deepClone(res.data).reverse())
						factList.value = res.data.slice(0, 5)
				} catch (error) {
					commonJs.showMessage(error)
				}
			},
			fail(err) {
				commonJs.logger.debug(err, 'error')
			},
			complete() {
				
			}
		})
	}
	const setChart = (list) => {
		const yMax = Math.max(...(list.map(v => v.fact_money))) + 1
		opts.yAxis.data[0].max = Math.floor(yMax)
		const yMax1 = Math.max(...(list.map(v => v.open_rate))) + 1
		opts1.yAxis.data[0].max = Math.floor(yMax1)
		chartData.value = {
			categories: list.map(v => v.date),
			series: [{
				name: "营业额(万)",
				data: list.map(v => v.fact_money)
			}]
		}
		chartData1.value = {
			categories: list.map(v => v.date),
			series: [{
				name: "开台率(%)",
				data: list.map(v => v.open_rate)
			}]
		}
	}
	const clickTab = (index) => {
		act.value = index
    resetPages()
		getData()
		getLine()
	}

	const getTabs = () => {
		if (!commonJs.getShopList()) {
			uni.reLaunch({
				url: '/pages/login'
			})
			return
		}
		tabs.value = commonJs.getShopList()
	}

  /**
   * 跳转app
   */
  // const toHelper = () => {
	// 	const shop_id = tabs.value[act.value].shop_id
	// 	const staff_id = uni.getStorageSync('USERID')
	// 	const token = uni.getStorageSync('TOKEN')
	// 	const path = encodeURIComponent('/pages/app_helper/home/home')
	// 	// snssdk1128//:
	// 	let url =
	// 		`snssdk1128://?path=${path}&shop_id=${shop_id}&staff_id=${staff_id}&token=${encodeURIComponent(token)}`
	// 	// #ifdef APP-PLUS
	// 	if (plus.os.name == 'Android') {
	// 		plus.runtime.launchApplication({
	// 			pname: 'uni.UNIBBBB8F4',
	// 			extra: {
	// 				shop_id,
	// 				staff_id,
	// 				path,
	// 				token: encodeURIComponent(token)
	// 			}
	// 		}, function(res) {
	// 			console.log("启动失败");
	// 			console.log(JSON.stringify(res));
	// 		})
	// 	} else if (plus.os.name == 'iOS') {
	// 		plus.runtime.launchApplication({
	// 			action: url
	// 		}, function(res) {
	// 			console.log("启动失败");
	// 			console.log(JSON.stringify(res));
	// 		});
	// 	}
  //
	// 	// plus.runtime.openURL(url, function(res) {
	// 	// 	console.log("启动失败");
	// 	// 	console.log(JSON.stringify(res));
	// 	// })
	// 	// #endif
	// }


</script>

<style lang="scss" scoped>
	.title {
		font-weight: 500;
		font-size: 28rpx;
		color: var(--text-color);
	}

	.unit {
		font-size: 24rpx;
		color: var(--grey-text);
		font-weight: 100;
	}

	.money {
		font-size: 28rpx;
		color: var(--white-text);
		padding-top: 10rpx;
		font-weight: 500;
	}

	.red-text {
		color: #ff4b4e;
		font-size: 24rpx;
	}

	.green-text {
		color: #5cc94f;
		font-size: 24rpx;
	}

	.scroll {
		position: absolute;
		padding: 4rpx 30rpx 4rpx 30rpx;
		box-sizing: border-box;
	}

	.tab-text {
		color: var(--grey-text);
		font-weight: 500;
	}

	.tab-text-active {
		color: var(--white-text);
		font-weight: 600;
	}

	.gray-text {
		color: #888;
	}


	.top {
		position: sticky;
		left: 0;
		top: 0;
		height: 220rpx;
		padding: 10rpx 24rpx 0;
		background-color: #fff;
		z-index: 100;

		.tabs {}
	}

	.cavas {
		width: 100%;
		height: 450rpx;
	}

	.tab-item {
		padding: 6rpx 20rpx;
		display: flex;
		font-size: 26rpx;
		font-weight: 500;
		&>view {
			flex-shrink: 0;
			flex: 1;

			&:first-child {
				// flex: .8;
				// width: 17% !important;
			}
		}
	}

	.tab-head {
		padding: 0 20rpx 6rpx 20rpx;
		font-weight: 300;
		border-radius: 10rpx;
	}

	.gap-box {
		width: 100%;
		height: 12rpx;
		background-color: #f3f3f3;
	}
</style>